package com.jbm.core.common;

import com.google.protobuf.GeneratedMessage;
import com.jbm.core.client.PlayCallback;
import com.jbm.core.iface.IAcross;
import com.jbm.core.pb.PBIAcross;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

/**
 * Created by root on 17-3-31.
 */
public class MainHandler extends IoHandlerAdapter
{
	protected static Logger s_logger = LoggerFactory.getLogger(MainHandler.class);
	protected PlayCallback m_playcallback;
	protected P2PServer m_p2piface;

	protected IAcross m_iacross;

	public MainHandler ( )
	{
	}

	public MainHandler ( PlayCallback callback )
	{
		m_playcallback = callback;
	}

	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		s_logger.error("main client端发送异常...", cause);
	}

	public void messageReceived(IoSession session, Object message) throws Exception
	{
		AutoCall.g_autocall.IO(session,null,(PBIAcross.IAcross)message,MainServer.getG_server().getM_local_id(),MainServer.getG_server().getM_server_type());
	}

	public void messageSent(IoSession session, Object message) throws Exception
	{
		ConnectAgent ca = (ConnectAgent) session.getAttribute("CA_Key");

		int acc_id;

		if ( ca != null )
		{
			IAccount ia = ca.getM_iaccount();

			if ( ia != null )
				acc_id = ia.getM_account_id();
			else
				acc_id = 0;
		}else
			acc_id = 0;

		if ( message instanceof byte[])
		{
//			s_logger.info("Sent byte[]...");
			if (MainServer.getG_server().getM_server_type() == MainServer.Server_type_Server)
				SysLog.g_syslog.MakeLog(SysLog.SYS_LOG_LEVEL_DEBUG,"%d Sent byte[]...", acc_id);
		}else
		{
//			s_logger.info("Sent:\n" + message.toString());
			if (MainServer.getG_server().getM_server_type() == MainServer.Server_type_Server)
				SysLog.g_syslog.MakeLog(SysLog.SYS_LOG_LEVEL_DEBUG,"%d Sent:\n%s",acc_id, message.toString());
		}
	}

	public void sessionCreated(IoSession session) throws Exception {
		s_logger.info("客户端与服务端创建连接...port:"+((InetSocketAddress) session.getRemoteAddress()).getPort());
		session.setAttribute("PROTOC_TYPE", "32");
		session.setAttribute("0-1.0_first req", "1");
		session.setAttribute("IFileObject",null);
		String clientIP = ((InetSocketAddress) session.getRemoteAddress()).getAddress().getHostAddress();
//		session.setAttribute("KEY_SESSION_CLIENT_IP", clientIP);
//		session.setAttribute("LOGIN_ID", "0");
//		session.setAttribute("MEMBER_ID", "0");
//		session.setAttribute("SELLER_ID", "0");
	}

	public void sessionClosed(IoSession session) throws Exception
	{
		ConnectAgent ca = (ConnectAgent)session.getAttribute("CA_Key");

		if ( ca != null )
		{
			ca.Die();
			s_logger.error("Main client 关闭..."+ca.getM_iaccount().getM_account_id());
		}else
			s_logger.error("Main client 关闭...");
	}
}
